package com.credithc.eagleeye.api.config;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.credithc.eagleeye.api.interceptor.TokenHandlerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.ArrayList;
import java.util.List;
/**
 * 描 述: <br/>
 * 作 者: zhangjin<br/>
 * 创 建：2018年02月11日<br/>
 * 版 本：v1.0.0<br>
 * <p>
 * 历 史: (版本) 作者 时间 注释 <br/>
 */
@Configuration
@Slf4j
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    @Autowired
    private ApplicationConfig applicationConfig;
    @Autowired
    private TokenHandlerInterceptor  tokenHandlerInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(tokenHandlerInterceptor).addPathPatterns("/**").excludePathPatterns("/login").excludePathPatterns("/status").excludePathPatterns("/alertInfo");
    }
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        String apiAllowOrigins = StringUtils.trimToEmpty(applicationConfig.getAllowOrigins());
        registry.addMapping("/**")
                //从配置中心获取允许跨域的域名
                .allowedOrigins(StringUtils.split(apiAllowOrigins, ","))
                .allowedMethods( "HEAD","POST","GET","OPTIONS")
                .allowCredentials(true)
                .maxAge(3600);
        super.addCorsMappings(registry);
        log.info("eagle-api允许跨域调用的域名初始化为:{}",apiAllowOrigins);
    }

    /**
     * 利用fastjson替换掉jackson
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //1.构建了一个HttpMessageConverter  FastJson   消息转换器
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        //2.定义一个配置，设置编码方式，和格式化的形式
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        //3.设置成了PrettyFormat格式
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        //4.处理中文乱码问题
        List<MediaType> fastMediaTypes =  new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);
        //5.将fastJsonConfig加到消息转换器中
        fastConverter.setFastJsonConfig(fastJsonConfig);
        converters.add(fastConverter);
    }
}
